package com.ark.frigate.shell.utils.deploy.module.config;

import com.ark.frigate.shell.utils.JSchUtils;
import com.ark.frigate.shell.utils.deploy.module.DeployComponentCore;
import com.ark.frigate.shell.utils.deploy.po.MachinePo;
import com.ark.frigate.shell.utils.dto.ResultDto;
import lombok.extern.slf4j.Slf4j;

/**
 * TODO
 *
 * @author zengweilong
 * @date 7/15/21 5:25 PM
 */
@Slf4j
public class ConfigCodeDeployImpl extends DeployComponentCore {


    @Override
    public int deployFile(MachinePo machinePo) {
        log.info("开始部署中...{}", machinePo.getHost());
        JSchUtils jSch = connection(machinePo);
        try {
            String workspace = machinePo.getWorkspace();
            String tmpDir = "tmp_config";
            // 进入工作目录
            String command = "cd " + workspace;
            // 解压上传的文件到指定目录
            command += "; unzip " + machinePo.getFileName() + " -d " + tmpDir;
            // 清空原来的  jar  包
            command += "; rm -rf " + machinePo.getBackPath() + "/lib/*.jar";
            // 清空原来的  xml 文件
            command += "; rm -rf " + machinePo.getBackPath() + "/config/mybatis/mappers/*.xml";
            // 复制新的  jar  包
            command += "; cp -r " + tmpDir + "/" + machinePo.getBackPath() + "/lib/*.jar " + machinePo.getBackPath() + "/lib/";
            // 复制新的 xml 包
            command += "; cp -r " + tmpDir + "/" + machinePo.getBackPath() + "/config/mybatis/mappers/*.xml " + machinePo.getBackPath() + "/config/mybatis/mappers/";
            // 清理上传的文件和解压的目录
            command += "; rm -rf " + tmpDir + " " + machinePo.getFileName();

            log.info("IP=[{}], 执行部署命令=[{}]", machinePo.getHost(), command);
            ResultDto resultDto = jSch.execCommand(command);
            log.info("IP=[{}], 执行部署结果=[{}]", machinePo.getHost(), resultDto);
            return resultDto.getCode();
        } catch (Exception e) {
            log.error("部署失败deploy.FAIL", e);
        } finally {
            if (jSch != null) {
                jSch.closeSession();
            }
        }
        return -1;
    }
}
